package com.jeesite.modules.utils.wx;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.http.HttpClientUtils;
import com.jeesite.modules.component.CatchService;
import com.jeesite.modules.ic.entity.IcUser;
import com.jeesite.modules.utils.wx.vo.PushCard;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 微信小程序
 */
@Service
@Slf4j
public class WxMini {

    @Value("${wx.mini.appid}")
    private String appId;

    @Value("${wx.mini.secret}")
    private String secret;


    @Value("wx6dfc84f4de25c91e")
    private String appIdGongzhong;

    @Value("781eb87f7ad975f7b774c0cce42753b0")
    private String secretGongzhong;

    @Autowired
    private CatchService  catchService;


    public String getAccessToken(){
        String access_token = catchService.get("ACCESS_TOKEN");
        if(StringUtils.isEmpty(access_token)){
            String s = HttpClientUtils.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret);
            log.info("ACCESS_TOKEN:"+s);
            JSONObject jsonObject = JSONObject.parseObject(s);
            access_token = jsonObject.getString("access_token");
            Integer expires_in = jsonObject.getInteger("expires_in");
            catchService.add("ACCESS_TOKEN",access_token, expires_in-600,TimeUnit.SECONDS);
        }
        return access_token;
    }

    public String getOpenId(String code){

        String sopenid = HttpClientUtils.get("https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid="+appId+"&secret="+secret+"&js_code="+code);
        log.info("OPENID:"+sopenid);
        JSONObject jsonObject = JSONObject.parseObject(sopenid);
        if(jsonObject.getIntValue("errcode")==48001){
            catchService.delete("ACCESS_TOKEN");
            sopenid = getOpenId(code);
        }
        return sopenid;
    }

    public String getMobile(String code,String access_token){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",code);
        String mobile = HttpClientUtils.ajaxPostJson("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+access_token,jsonObject.toJSONString());
        log.info("MOBILE:"+mobile);
        if(jsonObject.getIntValue("errcode")==48001){
            catchService.delete("ACCESS_TOKEN");
            mobile = getMobile(code,access_token);
        }
        return mobile;
    }

    public String getAccessTokenGongZhong(){
        String access_token = catchService.get("ACCESS_TOKEN_Gongzhong");
        log.info("ACCESS_TOKEN_Gongzhong缓存:"+access_token);
        if(StringUtils.isEmpty(access_token)){
            String s = HttpClientUtils.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appIdGongzhong+"&secret="+secretGongzhong);
            log.info("ACCESS_TOKEN_Gongzhong:"+s);
            JSONObject jsonObject = JSONObject.parseObject(s);
            access_token = jsonObject.getString("access_token");
            Integer expires_in = jsonObject.getInteger("expires_in");
            catchService.add("ACCESS_TOKEN_Gongzhong",access_token, expires_in-600,TimeUnit.SECONDS);
        }
        return access_token;
    }

    /**
     * 公众号获取UnionID
     * @param openId
     * @return
     */
    public String getUnionIdGongzhong(String openId){
        String accessTokenGongZhong = getAccessTokenGongZhong();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessTokenGongZhong+"&openid="+openId+"&lang=zh_CN";
        String s = HttpClientUtils.get(url);
        log.info("获取UnionID:"+s);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String unionid = null;
        if(jsonObject.getIntValue("errcode")==48001){
            catchService.delete("ACCESS_TOKEN_Gongzhong");
            unionid = getUnionIdGongzhong(openId);
        }else{
            unionid = jsonObject.getString("unionid");
        }
        return unionid;
    }

    /**
     * 推送微信模板消息
     * @return
     */
    public void pushmsg(PushCard pushCard){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser",pushCard.getOpenId());
        jsonObject.put("template_id","If1K48hpPhc5hukNiY5eTdlEUmmNsZjoqZa-e_79sGE");
        JSONObject miniprogram = new JSONObject();
        miniprogram.put("appid",appId);
        miniprogram.put("pagepath","pages/card/info?id="+pushCard.getCardId());
        jsonObject.put("miniprogram",miniprogram);
        JSONObject data = new JSONObject();
        data.put("character_string93",JSONObject.parseObject("{\"value\":\""+pushCard.getIccid()+"\"}"));
        data.put("thing2",JSONObject.parseObject("{\"value\":\""+(StringUtils.isNotEmpty(pushCard.getTitle())?pushCard.getTitle():"")+"\"}"));
        data.put("character_string25",JSONObject.parseObject("{\"value\":\""+(StringUtils.isNotEmpty(pushCard.getImei())?pushCard.getImei():"")+"\"}"));
        data.put("time4",JSONObject.parseObject("{\"value\":\""+pushCard.getTime()+"\"}"));
        data.put("thing38",JSONObject.parseObject("{\"value\":\""+pushCard.getContent()+"\"}"));
        jsonObject.put("data",data);
        log.error("推送参数："+jsonObject);
        String accessTokenGongZhong = getAccessTokenGongZhong();
        String post = HttpClientUtils.ajaxPostJson("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessTokenGongZhong, jsonObject.toJSONString());
        JSONObject result = JSONObject.parseObject(post);
        log.error("推送返回："+result);
    }

    /**
     * 创建自定义菜单
     * @param jsonObject
     */
    public boolean createMenu(JSONObject jsonObject){
        String accessTokenGongZhong = getAccessTokenGongZhong();
        String post = HttpClientUtils.ajaxPostJson("https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+accessTokenGongZhong, jsonObject.toJSONString());
        log.info("自定义菜单创建："+post);
        JSONObject result = JSONObject.parseObject(post);
        if(result.getIntValue("errcode")==0){
            return true;
        }else{
            return false;
        }
    }


}
